import 'dart:convert';
import 'package:dio/dio.dart';
import 'package:convert/convert.dart';
import 'package:crypto/crypto.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_app/common/Global.dart';
import 'LoginEntity.dart';

class Login extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _HttpLoginState();
}

class _HttpLoginState extends State<Login> {
  var _userName = "17358989747";
  var _userPassword = "123456";
  var _responseText;

  var _loginToken = "";

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("登录"),
      ),
      body: Center(
        child: buildColumn(),
      ),
    );
  }

  Column buildColumn() {
    return Column(
        children: [
          TextField(
            controller: TextEditingController(
              text: "17358989747"
            ),
            //自动获取焦点
            autofocus: true,
            decoration: InputDecoration(
              labelText: "用户名",
              prefixIcon: Icon(Icons.call),
            ),
            maxLength: 20,
            maxLines: 1,
            onChanged: (str) {
              _userName = str;
            },
          ),
          TextField(
            controller: TextEditingController(
                text: "123456"
            ),
            decoration: InputDecoration(
              labelText: "密码",
              prefixIcon: Icon(Icons.public_rounded),
            ),
            maxLines: 1,
            onChanged: (str) {
              _userPassword = str;
            },
          ),
          MaterialButton(
              child: Text("下一步"),
              onPressed: () {
                dio();
              }),
          Expanded(child: Text(_responseText!=null? _responseText:""))
        ],
      );
  }

  Future<void> dio() async{
    Dio dio =  Dio();
    dio.options.baseUrl = "http://gateway.hp.goalgo.cn:42770";
    dio.options.connectTimeout = 5000;
    dio.options.receiveTimeout = 2000;

    _loginToken = Global().getLoginToken();
    //请求头
    Map<String,dynamic> head = {
      "type" : "android",
      "system" : "OA",
      "hardware" : "Android",
      "loginToken" : _loginToken
    };
    //请求参数
    Map<String,dynamic> requestBody = {
      "username":_userName,
      "password":generateMD5(_userPassword),//md5加密
      "deviceToken":"",
      "deviceType":4,
      "system":"oa"
    };
    dio.options.headers.addAll(head);
    //请求
    debugPrint("head:->"+head.toString());
    debugPrint("request:->"+requestBody.toString());
    var response=await dio.post("/login", queryParameters: requestBody);
    debugPrint("response:->"+response.toString());
    //json转map
    Map responseMap = json.decode(response.toString());
    //map转实体类
    var loginInfo = LoginEntity.fromJson(responseMap);
    Global().saveLoginToken(loginInfo.loginToken);
    setState(() {
      _responseText = loginInfo.returnMessage;
    });
  }

  // md5 加密
  String generateMD5(String data) {
    var content = new Utf8Encoder().convert(data);
    var digest = md5.convert(content);
    // 这里其实就是 digest.toString()
    return hex.encode(digest.bytes);
  }
}
